package com.ld.security.shop.crawler.modules.re.crawler.edd;

import com.ld.security.common.core.util.JsonUtil;
import com.ld.security.common.core.util.ReflectionUtil;
import com.ld.security.shop.crawler.modules.re.constant.CrawlerConstant;
import com.ld.security.shop.crawler.modules.re.crawler.BaseCrawler;
import com.ld.security.shop.crawler.modules.re.entity.ReBook;
import com.ld.security.shop.crawler.modules.re.entity.ReDetails;
import com.ld.security.shop.crawler.modules.re.service.IReBookService;
import com.ld.security.shop.crawler.modules.re.service.IReDetailsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;

@Component
public class EddReDetailsCrawler extends BaseCrawler<ReDetails> {

    @Autowired
    IReDetailsService iReDetailsService;

    @Autowired
    IReBookService iReBookService;

    public EddReDetailsCrawler() {
        super( CrawlerConstant.projectCode.edd);
    }

    @Override
    public ReDetails dataCrawler(String url) {
        url = this.newRequest(url);
        ReDetails o = super.dataCrawler(url);
        iReDetailsService.save(o);
        this.parsing(o);
        return o;
    }


    public String getId(String url){
        int x = url.indexOf("products")+"products".length()+1;
        int y = url.indexOf(".html");
        String id = url.substring(x,y);
        return id;
    }


    public String newRequest(String url){
        String id = this.getId(url);
        String baseUrl="http://e.dangdang.com/media/api.go?action=getMedia&deviceSerialNo=html5&macAddr=html5&channelType=html5&permanentId=20190514092925338198474251478890165&returnType=json&channelId=70000&clientVersionNo=6.8.0&platformSource=DDDS-P&fromPlatform=106&deviceType=pconline&token=&refAction=browse&saleId=1900687287&promotionType=1";
        Map<String,String> map = getUrlParams(baseUrl);
        map.put("saleId",id);
        return projectCode.getLabel()+"/media/api.go?"+toUrl(map);
    }

    public void parsing(   String id){
        ReDetails reDetails =  iReDetailsService.getById(id);
        parsing(reDetails);

    }
    /**
     * 解析爬虫数据
     */
    @Override
    public void parsing(   ReDetails reDetails){

        String json =  reDetails.getContent();
        Map data =  JsonUtil.toObject(json,Map.class);

        List<Map> maps =  getValue(data,"data","mediaSale","mediaList");
        for (Map map : maps) {
            ReBook reBook =  ReflectionUtil.clone(map,ReBook.class);
            iReBookService.save(reBook);
        }
    }


}

